<?php

/**
 * 平行云仓订单
 * @author chenshubo
 */
namespace App\Service\VendorClient\ShopycApi;
use App\Service\Code\Normal;
use App\Service\BaseService;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;
use App\Service\HttpServer\Http;
use App\Service\AppService\SystemCacheConfigService;

class ShopSameLevelYunCangApiClient extends BaseService
{
    protected $clientConfig;
    
    /**
     * 初始化配置
     * @param array $apiBody
     */
    public function __construct($apiBody=[])
    {
        $this->clientConfig = $apiBody;
    }
    
    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        $supplierGoods  = $param['supplierGoodsInfo'];
        //下单信息
        $orderInfo      = $param['order'];
        //下单商品组
        $userGoodsList  = $supplierGoods['userGoodsList'];
        //原始商品数据组
        $goodsList      = $supplierGoods['goodsList'];
        
        $yc_goods = array_map(function( & $value) use ($goodsList) {
            $value['goodsSku'] = $goodsList[$value['goodsSku']]['supplierSKUCode'];
            return $value;
        },$orderInfo['goods']);
        
        //重新计算订单金额
        $weight = $goodsMoney = 0 ;
        foreach ($yc_goods as $goods )  {
            $singleGoodsMoney = bcmul((string)$goods['goodsPrice'], (string)$goods['goodsNum'],2);
            $goodsMoney = bcadd((string)$goodsMoney, (string)$singleGoodsMoney,2);
            $weight = bcadd((string)$weight, (string)$goods['freight'],2);
        }
        
        $orderMoney = bcadd((string)$weight, (string)$goodsMoney,2);
        $discountMoney              = $orderInfo['discountMoney'] ?? 0.00;
        $orderInfo['freight']       = $weight;
        $orderInfo['orderMoney']    = bcsub((string)$orderMoney,(string)$discountMoney,2);
        $orderInfo['orderSn']       = $orderInfo['supplier_psn'];
        $orderInfo['goods']         = $yc_goods;
        $orderInfo['isPayDeclare']  = 1;
        
        unset($orderInfo['order_sn'],$orderInfo['supplier_psn']);
        if( isset($orderInfo['isSplitOrder']) ) { unset($orderInfo['isSplitOrder']);}
        
        //是否是子系统订单
        $orderInfo['isChildSystem'] = 1;
        if( isset($orderInfo['order_type']) ) { unset($orderInfo['order_type']);}
        if( isset($orderInfo['isNotTopSystem']) ) { unset($orderInfo['isNotTopSystem']);}
        
        $requestParam = [
            'requestMethod' => 'createOrder',
            'requestData'   => $orderInfo
        ];
        return $this->execute($requestParam);
    }

    /**
     * 取消订单
     * @param array $params
     * @return mixed
     */
    public function cancelOrder( $params = [] )
    {
        $params['order']['orderSn']         = $params['supplierOrder']['supplier_psn'];
        $params['order']['orderNo']         = $params['supplierOrder']['supplier_csn'];
        $params['order']['isSingleOrder']   = true;
        $requestParam = [
            'requestMethod' => 'OrderCancel',
            'requestData'   => $params['order']
        ];
        return $this->execute($requestParam);
    }

    /**
     * 订单支付
     * @param array $params
     * @return mixed
     */
    public function payOrder( $params = [] )
    {
        $params['order']['orderSn']         = $params['supplierOrder']['supplier_psn'];
        $params['order']['orderNo']         = $params['supplierOrder']['supplier_csn'];
        $params['order']['isSingleOrder']   = true;
    
        if( isset($params['order']['thirdPartOrderSn']) ) {
            unset($params['order']['thirdPartOrderSn']);
        }
        
        $requestParam = [
            'requestMethod' => 'OrderPay',
            'requestData'   => $params['order']
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * 订单售后
     * @param array $params
     * @return mixed
     */
    public function orderAfterSale( $params = [] )
    {
        $params['order']['order_sn']        = $params['supplierOrder']['supplier_psn'];
        $params['order']['orderNo']         = $params['supplierOrder']['supplier_csn'];
        $params['order']['isSingleOrder']   = true;
        $requestParam = [
            'requestMethod' => 'OrderAfterSale',
            'requestData'   => $params['order']
        ];
        return $this->execute($requestParam);
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {        
        $columns = ['appid','key','baseurl'];
        $res = SystemCacheConfigService::instance()->checkAllowApiColumnsByFields($this->clientConfig,$columns);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $param['appid']         = $this->clientConfig['appid'];
        $param['requestData']   = rawurlencode(json_encode($param['requestData']));
        $param['sign']          = strtoupper(Http::getSign($param,$this->clientConfig['key']));
        if( empty($this->clientConfig['baseurl']) ) {
            return Normal::returnCode(Normal::FAIL,"当前仓库参数baseurl未配置");
        }
        
        $applyUrl = $this->clientConfig['baseurl'];
        $header = [
            "Content-Type: application/json",
            "Accept:application/json"
        ];
        
        $method = $param['requestMethod'];
        if( $method != 'createOrder' )
        {
            $parameter = [
                [
                    'tag'       => 'ShopSameLevelYunCang_'.$method,
                    'uid'       => IdService::instance()->getOtherID(),
                    'url'       => $applyUrl,
                    'data'      => $param,
                    'method'    => 'post',
                    'format'    => 'x-www-form-urlencoded',
                    'header'    => [],
                ],
            ];
            
            $resTask    = TaskWorker::instance()->addTask($parameter);
            $resTask    = current($resTask);
            $response   = $resTask['response']['result'];
            $result     = @json_decode($response,true);
            if( isset($result['code']) && $result['code'] == Normal::SUC ) {
                return $result;
            } else {
                $msg = isset($result['msg']) ? $result['msg'] : $response ;
                return Normal::returnCode(Normal::FAIL,$msg);
            }
        }
        
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'url'       => $applyUrl,
            'data'      => $param,
            'format'    => 'x-www-form-urlencoded'
        ]);
    }
}